package com.yuba.web.service.impl.front;

import cn.dev33.satoken.secure.BCrypt;
import cn.hutool.core.util.RandomUtil;
import com.yuba.common.core.constant.Constants;
import com.yuba.common.core.domain.model.RegisterBody;
import com.yuba.common.core.enums.UserType;
import com.yuba.common.core.exception.user.UserException;
import com.yuba.common.core.utils.MessageUtils;
import com.yuba.common.core.utils.regex.RegexValidator;
import com.yuba.common.web.config.properties.CaptchaProperties;
import com.yuba.front.domain.bo.FrontUserBo;
import com.yuba.front.service.IFrontUserService;
import com.yuba.web.service.IRegisterStrategy;
import com.yuba.web.service.SysRegisterService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 前台用户注册策略
 *
 * @author modakai
 */
@Slf4j
// 值来自 @code UserType.FRONT_USER
@Service("front_user" + IRegisterStrategy.BASE_NAME)
@RequiredArgsConstructor
public class FrontUserRegisterStrategy implements IRegisterStrategy {

    private static final Long DEFAULT_AVATAR = 1866492993474756609L;

    private final SysRegisterService registerService;
    private final CaptchaProperties captchaProperties;
    private final IFrontUserService userService;

    @Override
    public void register(RegisterBody body) {
        String username = body.getUsername();
        RegexValidator.validatePhoneStrict(username, "user.mobile.phone.number.not.valid");

        String password = body.getPassword();
        // 1. 校验用户类型是否存在
        String userType = UserType.getUserType(body.getUserType()).getUserType();

        // 2. 验证码校验
        boolean captchaEnabled = captchaProperties.getEnable();
        // 验证码开关
        if (captchaEnabled) {
            registerService.validateCaptcha(null, username, body.getCode(), body.getUuid());
        }

        // 3. 验证用户名是否已存在
        FrontUserBo userBo = new FrontUserBo();
        userBo.setUsername(username);
        userBo.setNickname("渔友" + RandomUtil.randomNumbers(4));
        userBo.setAvatar(DEFAULT_AVATAR);
        userBo.setUserType(userType);
        userBo.setPassword(BCrypt.hashpw(password));

        boolean exist = userService.isExist(userBo);
        if (exist) {
            throw new UserException("user.register.save.error", username);
        }

        // 4. 注册用户
        boolean regFlag = userService.registerUser(userBo);
        if (!regFlag) {
            throw new UserException("user.register.error");
        }
        // 5. 触发注册日志
        registerService.recordLoginInfo(null, username, Constants.REGISTER, MessageUtils.message("user.register.success"));
    }
}
